import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:baselib/utils/log_util.dart';
import 'package:framelib/config/api_config.dart';
import 'package:nim_core/nim_core.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:agora_rtc_engine/agora_rtc_engine.dart';

class AgoraSDKUtil{
  static final AgoraSDKUtil _singleton = AgoraSDKUtil._internal();
  static AgoraSDKUtil get instance => AgoraSDKUtil();
  factory AgoraSDKUtil() {
    return _singleton;
  }
  AgoraSDKUtil._internal();

  static RtcEngine _engine;

  static RtcEngine get engine => _engine; // 初始化应用

  init() async{
    // 获取权限
    await [Permission.microphone, Permission.camera].request();
    // 创建 RtcEngine
    try{
      _engine = await createAgoraRtcEngine();
      // 初始化 RtcEngine，设置频道场景为直播场景
      await _engine.initialize(const RtcEngineContext(
        appId: ApiConfig.agora_app_id,
        channelProfile: ChannelProfileType.channelProfileLiveBroadcasting,

      )).then((value){
        LogUtil.d("AgoraSDKUtil--->初始化成功");
      });
    }catch(e){
      LogUtil.d("AgoraSDKUtil--->初始化失败，e=${e?.toString()}");
    }
  }


  ///消息监听
  registerEventHandler(
      Function(RtcConnection connection, int elapsed) onJoinChannelSuccess,
      Function(RtcConnection connection, int remoteUid, int elapsed) onUserJoined,
      Function(RtcConnection connection, int remoteUid, UserOfflineReasonType reason) onUserOffline,
      ){
    _engine.registerEventHandler(
      RtcEngineEventHandler(
        onJoinChannelSuccess: (RtcConnection connection, int elapsed) {
          LogUtil.d("AgoraSDKUtil--->local user ${connection.localUid} joined");
          if(onJoinChannelSuccess!=null)onJoinChannelSuccess(connection,elapsed);
        },
        onUserJoined: (RtcConnection connection, int remoteUid, int elapsed) {
          LogUtil.d("AgoraSDKUtil--->remote user $remoteUid joined");
          if(onUserJoined!=null)onUserJoined(connection,remoteUid,elapsed);
        },
        onUserOffline: (RtcConnection connection, int remoteUid, UserOfflineReasonType reason) {
          LogUtil.d("AgoraSDKUtil--->remote user $remoteUid left channel");
          if(onUserOffline!=null)onUserOffline(connection,remoteUid,reason);
        },
      ),
    );
  }
  //开启视频
  Future<void> startPreview() async{
    //joinChannel e=AgoraRtcException(-102, null)
    try{
      await _engine.enableVideo();
      await _engine.setVideoEncoderConfiguration(
        const VideoEncoderConfiguration(
          dimensions: VideoDimensions(width: 640, height: 360),
          frameRate: 15,
          bitrate: 0,
        ),
      );
      await _engine.startPreview();
    }catch(e){
      LogUtil.d('AgoraSDKUtil-->startPreview e=${e?.toString()}');
    }
  }
  //加入频道，设置用户角色为主播
  Future<void> joinChannel(
      String token, String channelId,int uid, { ChannelMediaOptions options}) async{
    LogUtil.d('joinChannel-->token=$token,channelId=$channelId,uid=$uid');
    try{
      return await _engine.joinChannel(
        token: token,
        channelId: channelId,
        options: options??(const ChannelMediaOptions(
            channelProfile: ChannelProfileType.channelProfileLiveBroadcasting,
            clientRoleType: ClientRoleType.clientRoleBroadcaster)),
        uid: uid??0,
      );
    }catch(e){
      LogUtil.d('AgoraSDKUtil-->joinChannel e=${e?.toString()}');
      return null;
    }
  }
  //离开频道
  Future<void> leaveChannel() async{
    try{
      await _engine.leaveChannel();
      // await engine.release();
    }catch(e){
      LogUtil.d('AgoraSDKUtil-->leaveChannel e=${e?.toString()}');
    }

  }
}
